package com.jiufen.Aop;

import com.jiufen.Mapper.OperateLogMapper;
import com.jiufen.Pojo.OperateLog;
import com.jiufen.Utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
@Slf4j
public class LogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    //使用注解进行切面
    @Around("@annotation(com.jiufen.anno.LogOperate)")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {

        //执行方法
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long executionTime = System.currentTimeMillis() - start;
        log.info("Method execution time: {} ms", executionTime);
        //构建日志对象
        OperateLog operLog = new OperateLog();
        operLog.setOperateEmpId(getCurrentEmployeeId()); // 假设有一个方法可以获取当前操作人ID
        operLog.setOperateTime(LocalDateTime.now()); // 记录当前操作时间
        operLog.setClassName(joinPoint.getTarget().getClass().getName());   // 记录操作的类名
        operLog.setMethodName(joinPoint.getSignature().getName());   // 记录操作的方法名
        operLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));  // 记录操作的参数
        operLog.setCostTime(executionTime);  // 记录操作耗时
        operLog.setReturnValue(result != null ? result.toString() : "null"); // 记录操作返回值

        //
        log.debug("日志对象为:{}", operLog);

        //写入日志记录表
        operateLogMapper.insert(operLog);
        // 返回原始方法结果
        return result;
    }

    /**
     * 获取  从filter 中操作 threadLocal 存入的 当前用户id
     * @return
     */
    private Integer getCurrentEmployeeId() {
        Integer currentId = CurrentHolder.getCurrentId();
        log.debug("LogAspect---当前员工登录ID为:{}",currentId);
        return currentId;
    }
}